package com.director.core.json.impl.gson;

import com.director.core.DirectMethod;
import com.director.core.DirectTransactionResult;
import com.director.core.annotation.DirectResult;
import com.director.core.annotation.Pattern;
import com.director.core.annotation.Serializer;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;

/**
 * @author Simone Ricciardi
 * @version 1.0, 11/29/2011
 */
public class GsonTransactionResult implements DirectTransactionResult {

   private JsonElement jsonResult;

   public GsonTransactionResult(final GsonBuilder gsonBuilder, DirectMethod directMethod, Object result) {
/*
      Object resultToParse = result;
      if(directMethod.hasReturnDataStrategy()) {
         resultToParse = new ResultWithStrategy(directMethod.getReturnDataStrategy(), result);
      }
*/
      if(directMethod.hasResultAnnotation()) {
         DirectResult directResult = directMethod.getResultAnnotation();
         for(Pattern pattern : directResult.includes()) {
            gsonBuilder.registerTypeAdapter(pattern.type(), new IncludeFieldsTypeAdapter(pattern.fields()));
         }
         for(Pattern pattern : directResult.excludes()) {
            gsonBuilder.registerTypeAdapter(pattern.type(), new ExcludeFieldsTypeAdapter(pattern.fields()));
         }
         for(Serializer serializer : directResult.serializers()) {
            gsonBuilder.registerTypeAdapter(serializer.type(), serializer.impl());
         }
      }

      this.jsonResult = gsonBuilder.create().toJsonTree(result);
   }

   public JsonElement getJsonResult() {
      return jsonResult;
   }
}
